import db from '../config/database.js';
import { generateToken, verifyPasswordBcrypt, hashPassword, generateSalt } from '../utils/crypto.js';
import { createSecureLogger } from '../utils/secureLoggingConfig.js';

// 安全日志记录器
const logger = createSecureLogger({
  service: 'DoctorController',
  logLevel: 'info'
});

// 初始化测试医生数据
const initializeTestData = async () => {
  try {
    // 检查是否已有admin用户
    const adminCheck = await db.query('SELECT COUNT(*) as count FROM doctors WHERE username = ?', ['admin']);

    if (!adminCheck || adminCheck.length === 0 || adminCheck[0].count === 0) {
      logger.info('Creating secure admin account...');

      // 数据库安全紧急修复：使用环境变量中的安全密码
      const adminPassword = process.env.ADMIN_SECURE_PASSWORD || 'default_secure_password_' + Date.now();
      const salt = generateSalt();
      const passwordHash = await hashPassword(adminPassword, salt);

      // 插入管理员数据
      await db.query(`
        INSERT INTO doctors (username, real_name, department, title, password_hash, salt, status, role)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `, ['admin', 'System Administrator', 'IT Security', 'Security Admin', passwordHash, salt, 1, 3]);

      logger.info('Secure admin account created', {
        username: 'admin',
        role: 'security_admin'
      });

      logger.warn('IMPORTANT: Change default password on first login');
    }
  } catch (error) {
    logger.logError(error, { operation: 'initialize_test_data' });
  }
};

// 医生登录
export const login = async (req, res) => {
  try {
    const { username, password } = req.body;

    // 参数验证
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空',
        data: null
      });
    }

    logger.info('医生登录尝试:', { username });

    // 查询医生信息
    const doctors = await db.query(
      'SELECT doctor_id, username, real_name, password_hash, salt, status, role, department, title FROM doctors WHERE username = ?',
      [username]
    );

    logger.info('查询结果:', { doctors: doctors, count: doctors.length });

    if (doctors.length === 0) {
      logger.warn('用户不存在:', { username });
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        data: null
      });
    }

    const doctor = doctors[0];
    logger.info('找到医生:', { doctor: doctor });

    // 检查账户状态
    if (doctor.status !== 1) {
      logger.warn('账户已禁用:', { username, status: doctor.status });
      return res.status(403).json({
        success: false,
        message: '账户已被禁用，请联系管理员',
        data: null
      });
    }

    // P0-B安全修复：彻底移除密码后门，只使用bcrypt验证
    let isPasswordValid = false;

    // 只允许使用安全的bcrypt密码验证
    try {
      isPasswordValid = await verifyPasswordBcrypt(password, doctor.password_hash);
    } catch (error) {
      logger.error('密码验证过程中发生错误:', {
        username: username,
        error: error.message
      });
      isPasswordValid = false;
    }

    if (!isPasswordValid) {
      logger.warn('密码验证失败:', { username });
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误',
        data: null
      });
    }

    // 生成JWT令牌
    const tokenPayload = {
      doctor_id: doctor.doctor_id,
      username: doctor.username,
      role: doctor.role,
      real_name: doctor.real_name
    };

    const token = generateToken(tokenPayload);

    // 记录登录成功
    logger.info('医生登录成功:', {
      doctor_id: doctor.doctor_id,
      username: doctor.username,
      real_name: doctor.real_name,
      role: doctor.role,
      department: doctor.department,
      title: doctor.title
    });

    // 返回登录结果
    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        doctor: {
          doctor_id: doctor.doctor_id,
          username: doctor.username,
          real_name: doctor.real_name,
          role: doctor.role,
          department: doctor.department,
          title: doctor.title,
          role_name: getRoleName(doctor.role)
        }
      }
    });

  } catch (error) {
    logger.error('医生登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试',
      data: null
    });
  }
};

// 获取角色名称
const getRoleName = (role) => {
  const roleMap = {
    1: '普通医生',
    2: '科室主任',
    3: '系统管理员'
  };
  return roleMap[role] || '未知角色';
};

// 获取当前医生信息
export const getCurrentDoctor = async (req, res) => {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { doctor_id } = req.user;

    const doctors = await db.query(
      'SELECT doctor_id, username, real_name, role, department, title FROM doctors WHERE doctor_id = ?',
      [doctor_id]
    );

    if (!doctors || doctors.length === 0) {
      return res.status(404).json({
        success: false,
        message: '医生信息不存在',
        data: null
      });
    }

    const doctor = doctors[0];
    doctor.role_name = getRoleName(doctor.role);

    res.json({
      success: true,
      message: '获取医生信息成功',
      data: doctor
    });

  } catch (error) {
    logger.error('获取医生信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取医生信息失败',
      data: null
    });
  }
};

// 初始化测试数据（仅开发环境）
export const initializeTest = async (req, res) => {
  try {
    if (process.env.NODE_ENV === 'production') {
      return res.status(403).json({
        success: false,
        message: '生产环境不允许此操作',
        data: null
      });
    }

    await initializeTestData();

    res.json({
      success: true,
      message: 'Test data initialization complete',
      data: {
        test_account: {
          username: 'admin',
          password: '[REDACTED]',
          role: 'Security Administrator',
          warning: 'Use secure password from environment variables'
        }
      }
    });

  } catch (error) {
    logger.error('初始化测试数据失败:', error);
    res.status(500).json({
      success: false,
      message: '初始化测试数据失败',
      data: null
    });
  }
};

// 自动初始化测试数据（服务器启动时调用）
// initializeTestData(); // 暂时注释掉以便测试API